package com.cellulam.framework.test.fake;

import com.cellulam.framework.cache.RedisClient;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 缓存
 */
@Slf4j
@Primary
@Component
public class MockRedisClient extends RedisClient {

    private Map<String, String> cache = Maps.newConcurrentMap();

    public MockRedisClient(StringRedisTemplate redisTemplate) {
        super(redisTemplate);
    }

    /**
     * 通过key获取
     *
     * @param key
     * @return
     */
    @Override
    public String get(String key) {
        return cache.get(key);
    }


    /**
     * 缓存 key - value, 且设置缓存时间
     *
     * @param key
     * @param value
     * @param timeout
     * @param timeUnit
     */
    @Override
    public void set(String key, String value, long timeout, TimeUnit timeUnit) {
        try {
            this.cache.put(key, value);
        } catch (Exception e) {
            log.error("set key [{}] error", key, e);
        }
    }

    /**
     * 删除 key
     *
     * @param key
     * @return
     */
    @Override
    public boolean delete(String key) {
        cache.remove(key);
        return true;
    }

    /**
     * 是否存在
     *
     * @param key
     * @return
     */
    @Override
    public boolean hasKey(String key) {
        return this.cache.containsKey(key);
    }

    public void clear() {
        this.cache.clear();
    }

    public void deleteReal(String key) {
       super.delete(key);
    }

    public String getReal(String key) {
        return super.get(key);
    }

    public void setReal(String key, String value, long timeout, TimeUnit timeUnit) {
        super.set(key, value, timeout, timeUnit);
    }
}
